package com.itheima.web;

import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.constant.MessageConstant;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.entity.Result;
import com.itheima.exception.CheckItemException;
import com.itheima.pojo.CheckItem;
import com.itheima.service.CheckItemService;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @version V1.0
 * @author: ljx
 * @date: 2020/01/09 12:00
 * @description:
 */
@RestController
@RequestMapping("/checkItem")
public class CheckItemController {

    @Reference(cluster = "failfast")  //服务请求不重试
    private CheckItemService checkItemService;

    @RequestMapping("/add")
    public Result add(@RequestBody CheckItem checkItem) {
        try {
            checkItemService.add(checkItem);
            return new Result(true, MessageConstant.ADD_CHECKITEM_SUCCESS);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.ADD_CHECKITEM_FAIL);
        }
    }

    @RequestMapping("/findPage")
    public PageResult findPage(@RequestBody QueryPageBean pageBean) {
        PageResult pageResult = null;
        try {
            pageResult = checkItemService.findPage(pageBean);
        } catch (Exception e) {
            //查询发生异常返回
            e.printStackTrace();
            PageResult pageResult1 = new PageResult(0L, null);
            pageResult1.setResult(new Result(false, MessageConstant.QUERY_CHECKITEM_FAIL));
            return pageResult1;
        }
        return pageResult;
    }

    @RequestMapping(value = "/update", method = RequestMethod.PUT)
    public Result update(@RequestBody CheckItem item) {
        Result result = null;
        try {
            result = checkItemService.update(item);
        } catch (Exception e) {
            e.printStackTrace();
            result = new Result(false, MessageConstant.EDIT_CHECKITEM_FAIL);
        }
        return result;
    }

    @RequestMapping(value = "/{id}", method = RequestMethod.DELETE)
    public Result delete(@PathVariable("id") String id) {
        Result result = null;
        try {
            System.out.println(id);
            result = checkItemService.delete(id);
        } catch (CheckItemException e) {
            return new Result(false, "该检查项存在其它数据的引用，不能删除！");
        } catch (Exception e) {
            result = new Result(false, MessageConstant.DELETE_CHECKITEM_FAIL);
        }
        return result;
    }

    @RequestMapping("/findAll")
    public Result findAllCheckItem() {
        List<CheckItem> itemList = checkItemService.findAllCheckItem();
        return new Result(true, MessageConstant.QUERY_CHECKITEM_SUCCESS, itemList);
    }
}
